<?php

/**
 * Block Controller.
 *
 * Helpful methods to make Controller.
 *
 * PHP versions 5
 * CAKEPHP versions 2.x
 * 
 * Green CMS - Content Management System and Framework Powerfull by Cakephp
 * Copyright 2012, GREEN GLOBAL CO., LTD (toancauxanh.vn)
 * 
 * CakePHP(tm) :  Rapid Development Framework (http://www.cakephp.org)
 * Copyright 2005-2011, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @author        Technology Lab No.I <tech1@toancauxanh.vn>
 * @link          
 * @package       Block.Controller
 * @since         Green v 1.0
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */
App::uses('BlockAppController', 'Block.Controller');

/**
 * Autocomple in PHP's IDE solution
 * 
 * @property Block $Block
 * 
 */
Class BlockController extends BlockAppController {

    /**
     * Use model class
     *
     * @var array
     */
    public $uses = array('Block.Block', 'Block.BlockRegion');

    /**
     * Called after the controller action.  
     *
     * @return void
     */
    public function beforeRender() {
        parent::beforeRender();
        if (in_array($this->request['action'], array('admin_add', 'admin_edit'))) {
            $layouts = $this->Dashboard->get($this->Block, 'layouts');
            if (empty($layouts)) {
                $layouts = array(null, array_keys($this->Block->schema()));
            }
            $this->set('_layouts', $layouts);
        }
    }

    public function beforeFilter() {
        parent::beforeFilter();
        if ($this->request['action'] === 'admin_index') {
            $this->Components->enable('Security');
        }
    }

    /**
     * Management data
     *
     * @return void
     */
    public function admin_index() {
        $themeName = !empty($this->request->query['theme']) ? $this->request->query['theme'] : $this->theme;        
        $layoutName = !empty($this->request->query['layout']) ? $this->request->query['layout'] : 'default';
        $db = ConnectionManager::getDataSource('default');
        $sql = "SELECT *";
        $sql .= " FROM config_themes,sub_sites";
        $sql .= " WHERE config_themes.themes_name LIKE '".$themeName."' and sub_sites.theme_id = config_themes.id";         
        $sub_site = $db->query($sql); 
        $theme_id = -1;               
        if($sub_site){
            $sub_site = Set::combine($sub_site,'{n}.sub_sites.id','{n}.sub_sites.subsite_name');               
        }  
        $themes = Configure::read('App.themes.enabled');
        $listTheme = Configure::read('App.themes.listTheme');        
        foreach($listTheme as $key=>$value){
            if(strcmp($value,$themeName)==0){
               $theme_id = $key;
            }
        }                       
        if (!in_array($themeName, $themes)) {
            $this->setFlash(__d('system', 'System error, %s theme is not available or not active', $themeName));
            $this->redirect(array('action' => 'index', 'ext' => false));
        }
        $layouts = $this->loadAppearance($themeName, 'layout');        
        if (empty($layouts[$layoutName])) {
            $layoutName = key($layouts);            
        }        
        $defaultSubSite = null;        
        if((!empty($this->request->query['sub_site']))&&($this->request->query['sub_site']!=null)){
            $defaultSubSite = $this->request->query['sub_site'];   
        }                
        if ($this->request->is('post')) {                       
            $data = array_merge(array('task' => '', 'id' => array(0)), $this->request->data['Paginate']);            
            switch (strtolower($data['task'])) {
                case 'add': {
                        $this->Dashboard->redirect(array('action' => 'add', $data['id'][0],$theme_id,$defaultSubSite,$layoutName));
                    }
                case 'copy': {
                        $this->Dashboard->redirect(array('action' => 'add',$data['id'][0],$theme_id,$defaultSubSite,$layoutName));
                    }
                case 'edit': {
                        $this->Dashboard->redirect(array('action' => 'edit',$data['id'][0],$theme_id,$defaultSubSite,$layoutName));
                    }
                case 'remove': {
                        $this->Dashboard->redirect(array('action' => 'delete',$data['id'][0],$theme_id,$defaultSubSite,$layoutName, '?' => array('keys' => $data['id'])));
                    }
                case 'save': {                                                
                        if (!empty($this->request->data['Block'])) {                                                 
                            foreach ($this->request->data['Block'] as $block) {
                                $this->Block->id = $block['id'];
                                if ($this->Block->saveField('weight', $block['weight'])) {
                                    $save = array(
                                        'block_id' => $block['id'],
                                        'theme' => $themeName . '.' . $layoutName. '.' .$defaultSubSite
                                    );
                                    $this->Block->Region->id = $this->Block->Region->field('id', $save);
                                    $this->Block->Region->save(array_merge($save, array('region' => $block['region'])));
                                }
                            }
                            $this->setFlash(__d('system', 'The %s setting has been saved', __d('system', 'Block')), 'success');
                            $this->redirect($this->request->here(false));
                        }
                    }
            }
        }         
        $themeRegions = $layouts[$layoutName];
        $themeRegions[-1] = __d('system', 'Disabled');
        $layouts = array_keys($layouts);
        $blockRegions = $this->Block->Region->find('list', array(
            'fields' => array(
                'block_id',
                'block_id',
                'region'
            ),
            'conditions' => array(
                'theme' => $themeName . '.' . $layoutName . '.' .$defaultSubSite ,
            ),
            'recursive' => -1));       
        $blocks = $this->Block->find('all', array(
            'fields' => array(
                'id', 'description', 'custom', 'weight', 'publish'
            ),
            'conditions'=>array('Block.theme_id'=>$theme_id),
            'order' => 'weight ASC',
            'recursive' => -1));        
        $this->Dashboard->translateMaps($this->Block, $blocks);
        $blocks = Set::combine($blocks, '{n}.Block.id', '{n}.Block');
        $blockCount = count($blocks);       
        $regions = $themeRegions;
        foreach ($regions as $region => &$options) {
            $options = array(
                'name' => $options,
                'blocks' => array()
            );
            if (empty($blockRegions[$region])) {
                continue;
            }
            $options['blocks'] = array_intersect_key($blocks, $blockRegions[$region]);
            foreach ($blockRegions[$region] as $block) {
                unset($blocks[$block]);
            }
        }
        if ($blocks) {
            $regions[-1]['blocks'] += $blocks;
        }
        $this->Dashboard->toolbar(__d('system', 'Blocks management'), array(
            'save' => array('action' => 'save', 'text' => __d('system', 'Save')),
            'add' => array('action' => 'add', 'text' => __d('system', 'Add')),
            'copy' => array('action' => 'copy', 'text' => __d('system', 'Copy')),
            'edit' => array('action' => 'edit', 'text' => __d('system', 'Edit')),
            'remove' => array('action' => 'removes', 'text' => __d('system', 'Delete'))
        ));
        $this->set(compact('themeName', 'layoutName','sub_site','theme_id','defaultSubSite','themeRegions', 'blockRegions', 'regions', 'layouts', 'themes', 'blockCount'));
    }

    /**
     * Add data
     *
     * @return void
     */
    public function admin_add($id = null,$theme_id=null,$subsite_id = null) {        
        $this->Dashboard->exists($this->Block, $id, false);
        $this->Dashboard->toolbar(__d('system', 'Add new Block'), array(
            'save' => array('action' => 'save', 'text' => __d('system', 'Save')),
            'next' => array('action' => 'save', 'text' => __d('system', 'Save & Add New')),
            'apply' => array('action' => 'save', 'text' => __d('system', 'Apply')),
            'cancel' => __d('system', 'Cancel')
        ));

        if ($this->request->is('post')) {
            $data = $this->request->data;                                                
            $this->Block->create();
            $task = strtolower($this->request->data['Paginate']['task']);
            if (empty($task) || $task === 'cancel') {
                $this->Dashboard->redirect(array('action' => 'index', 'ext' => false), true);
            }  
            if(!empty($data['Block']['style_block'])){
                $this->request->data['Block']['delta'] = $data['Block']['style_block'];                
            }
            if ($this->Block->save($this->request->data)) {                
                $this->setFlash(__d('system', 'The %s has been saved', __d('system', 'Block')), 'success');
                switch ($task) {
                    case 'next': {
                            $this->redirect($this->request->here(false));
                        }
                    case 'apply': {
                            $this->Dashboard->redirect(array('action' => 'edit', $this->Block->getInsertID()), false, true);
                        }
                }
                $this->Dashboard->redirect(array('action' => 'index', 'ext' => false), true);
            } else {
                $this->setFlash(__d('system', 'The %s could not be saved. Please, try again.', __d('system', 'Block')), 'error');
            }
        } elseif ($id) {
            $this->request->data = $this->Block->read(array('contain' => array('Role' => array('fields' => 'id'))), $id);
            $this->request->data['User']['Role'] = Set::combine($this->request->data, 'Role.{n}.id', 'Role.{n}.id');
        } else {
            $this->request->data = $this->Block->create();
        }
        $listBlock = $this->Block->find('list',array(
            'fields'=>array('Block.delta','Block.description'),
            'conditions'=>array('Block.theme_id'=>$theme_id,'Block.is_general'=>1)
        ));
        $this->loadModel('Node.NodeType'); 
        $listNodeTypes = $this->NodeType->find('list',array(
            'conditions'=>array('NodeType.sub_site'=>$subsite_id)
        ));               
        $roles = $this->Block->Role->find('list');
        $this->set(compact('roles', 'id','theme_id','listBlock','listNodeTypes'));
    }

    /**
     * Edit data
     *
     * @return void
     */
    public function admin_edit($id = null,$theme_id=null,$subsite_id = null) {
        $this->Dashboard->exists($this->Block, $id);
        $this->Dashboard->toolbar(__d('system', 'Edit Block #%s', $id), array(
            'save' => array('action' => 'save', 'text' => __d('system', 'Save')),
            'apply' => array('action' => 'save', 'text' => __d('system', 'Apply')),
            'remove' => array('action' => 'remove', 'text' => __d('system', 'Delete')),
            'cancel' => __d('system', 'Cancel')
        ));
        if ($this->request->is('post')) {
            $data = $this->request->data; 
            $task = strtolower($this->request->data['Paginate']['task']);
            switch ($task) {
                case 'remove': {
                        $this->Dashboard->redirect(array('action' => 'delete', '?' => array('keys' => $id)), false, true);
                    }
                case '':
                case 'cancel': {
                        $this->Dashboard->redirect(array('action' => 'index', 'ext' => false), true);
                    }
            }
            if(!empty($data['Block']['style_block'])){
                $this->request->data['Block']['delta'] = $data['Block']['style_block'];                
            }
            if ($this->Block->save($this->request->data)) {
                $this->setFlash(__d('system', 'The %s has been updated', __d('system', 'Block')), 'success');
                switch ($task) {
                    case 'apply': {
                            $this->redirect($this->request->here(false));
                        }
                }
                $this->Dashboard->redirect(array('action' => 'index', 'ext' => false), true);
            } else {
                $this->setFlash(__d('system', 'The %s could not be updated. Please, try again.', __d('system', 'Block')));
            }
        } else {
            $this->request->data = $this->Block->read(array('contain' => array('Role' => array('fields' => 'id'))), $id);
            $this->request->data['User']['Role'] = Set::combine($this->request->data, 'Role.{n}.id', 'Role.{n}.id');
        }
        $listBlock = $this->Block->find('list',array(
            'fields'=>array('Block.delta','Block.description'),
            'conditions'=>array('Block.theme_id'=>$theme_id,'Block.is_general'=>1)
        ));
        $this->loadModel('Node.NodeType'); 
        $listNodeTypes = $this->NodeType->find('list',array(
            'conditions'=>array('NodeType.sub_site'=>$subsite_id)
        )); 
        $roles = $this->Block->Role->find('list');
        $this->set(compact('roles', 'id','theme_id','listBlock','listNodeTypes'));
    }

    /**
     * Delete data
     *
     * @return void
     */
    public function admin_delete() {
        if (empty($this->request->query['keys'])) {
            $this->setFlash(__d('system', 'Select elements should be deleted from the list below!', __d('system', 'Block')));
        } else {
            $complete = 0;
            $message = null;
            $keys = (array) $this->request->query['keys'];
            foreach ($keys as $key) {
                if (!$this->Block->deleteAll(array('Block.id' => $key, 'Block.custom' => 1), true, true)) {
                    $message = $this->Block->getMessage();
                    if (!$message) {
                        $message = __d('system', 'Cannot delete row #%s.', $key);
                    }
                    break;
                } else {
                    $complete++;
                }
            }
            if ($message) {
                $message = __d('system', '<br/>The processing has stopped because : <b>%s</b>', $message);
            }
            $this->setFlash(__d('system', 'The %1$s has been deleted %2$s / %3$s rows.', __d('system', 'Block'), $complete, count($keys)) . $message, 'warning');
        }
        $this->Dashboard->redirect(array('action' => 'index', 'ext' => false), true);
    }

    /**
     * Translate data
     *
     * @return void
     */
    public function admin_translate($id = null, $language = null) {
        $this->Dashboard->exists($this->Block, $id);
        $locale = $this->Dashboard->getLocale($language);
        if (empty($locale)) {
            $this->setFlash(__d('system', 'The language code <b>%s</b> does not exist', $language));
        }
        $translateFields = $this->Dashboard->translateFields($this->Block);
        if (empty($translateFields)) {
            $this->setFlash(__d('system', 'The %s not be configured a multilingual', __d('system', 'Block')));
        }
        if (empty($locale) || empty($translateFields)) {
            $this->Dashboard->redirect(array('action' => 'index', 'ext' => false), true);
        }
        $this->Dashboard->toolbar(__d('system', 'Translate Block #%1$s to %2$s', $id, Router::getConfig('name', $language)), array(
            'save' => array('action' => 'save', 'text' => __d('system', 'Save')),
            'apply' => array('action' => 'save', 'text' => __d('system', 'Apply')),
            'remove' => array('action' => 'remove', 'text' => __d('system', 'Remove')),
            'cancel' => __d('system', 'Cancel')
        ));
        $this->Block->locale = $locale;
        if ($this->request->is('post')) {
            $task = strtolower($this->request->data['Paginate']['task']);
            switch ($task) {
                case 'remove': {
                        $this->Dashboard->removeTranslated($this->Block);
                        $this->setFlash(__d('system', 'The translated data of %s has been removed', __d('system', 'Block')), 'success');
                        $this->redirect($this->request->here(false));
                    }
                case '':
                case 'cancel': {
                        $this->Dashboard->redirect(array('action' => 'index', 'ext' => false), true);
                    }
            }
            if ($this->Block->translate($this->request->data)) {
                $this->setFlash(__d('system', 'The %s has been translated', __d('system', 'Block')), 'success');
                switch ($task) {
                    case 'apply': {
                            $this->redirect($this->request->here(false));
                        }
                }
                $this->Dashboard->redirect(array('action' => 'index', 'ext' => false), true);
            } else {
                $this->setFlash(__d('system', 'The %s could not be translated. Please, try again.', __d('system', 'Block')));
            }
        }
        $block = $this->Dashboard->getTranslated($this->Block, array_merge($translateFields, array('custom' => '')));
        $this->set(compact('locale', 'language', 'block', 'id'));
    }
    public function load_style_block($theme_id = null){
        $this->layout = 'ajax';
        $listBlock = $this->Block->find('list',array(
            'fields'=>array('Block.delta','Block.description'),
            'conditions'=>array('Block.theme_id'=>$theme_id,'Block.is_general'=>1)
        ));
        $this->set(compact('listBlock'));         
    }
}

?>
